package util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class TokenHelper {
    public static final String SING = "!@234%U?H23";
    /* public static String getToken(Map<String, String> map){
         //添加Token过期时间
         Calendar instance = Calendar.getInstance();
         instance.add(Calendar.DATE,7);
         HashMap<String, Object> map1 = new HashMap<>();
         //添加构成JWT的参数
         String token = JWT.create().withHeader(map1)//Header头信息
                 .withClaim("username", map.get("username"))//payload荷载信息,实际数据
                 .withClaim("password", map.get("password"))
                 .sign(Algorithm.HMAC256(SING));//签名 由头信息+荷载信息+密钥 组合之后进行加密得到
         return token;
     }*/
    public static String getToken(Map<Integer, String> map) {
        JWTCreator.Builder builder = JWT.create();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        //payload
        /*map.forEach((k,v) -> {
            builder.withClaim(k+"",v);
        });*/
        for(Integer urlId:map.keySet()){
            builder.withClaim(urlId+"",map.get(urlId));
        }
        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        String token = builder.sign(Algorithm.HMAC256(SING));//签名
        return token;
    }

    public static Collection<String> verify(String token, HttpServletResponse response) throws IOException {
        JSONObject message = new JSONObject();
        Collection<String> collections = new LinkedList<>();
        response.setContentType("application/json;charset=UTF-8");
        try {
            //创建验证对象
            DecodedJWT verify =
                    JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            //解码对象
            int size = verify.getClaims().size();
            for (int i = 1; i < size; i++) {
                collections.add(verify.getClaim(i+"").asString());
            }
            message.put("message","登陆成功");
        } catch (Exception e) {
            message.put("message", "没有权限");
            response.getWriter().println(message);
        }
        response.getWriter().println(message);
        return collections;
    }
}
